package client;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class ClientRegistry {
    private final Map<String, Client> clientRegistryMap;
    ReadWriteLock lock;

    public ClientRegistry() {
        lock = new ReentrantReadWriteLock();
        clientRegistryMap = new HashMap();
    }

    public boolean addClient(String clientName, Client client) {
        try {
            lock.writeLock().lock();
            if (clientRegistryMap.containsKey(clientName)) {
                return false;
            }
            clientRegistryMap.put(clientName, client);
            return true;
        } finally {
            lock.writeLock().unlock();
        }
    }

    public boolean removeClient(String clientName) {
        try {
            lock.writeLock().lock();
            if (!clientRegistryMap.containsKey(clientName)) {
                return false;
            }
            clientRegistryMap.remove(clientName);
            return true;
        } finally {
            lock.writeLock().unlock();
        }
    }

    public Client getClient(String clientName) {
        try {
            lock.readLock().lock();
            if (!clientRegistryMap.containsKey(clientName)) {
                return null;
            }
            return clientRegistryMap.get(clientName);
        } finally {
            lock.readLock().unlock();
        }
    }

    public boolean containsClient(String clientName) {
        try {
            lock.readLock().lock();
            if (clientRegistryMap.containsKey(clientName)) {
                return true;
            }
            return false;
        } finally {
            lock.readLock().unlock();
        }
    }
}
